#encoding:utf-8
import requests
from hashlib import md5

class Chaojiying_Client(object):

    def __init__(self, username, password, soft_id):
        self.username = username
        self.password = md5(password.encode('utf8')).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
        return r.json()

    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()



import random
headers = {
    "User-Agent":"User-Agent, Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv,2.0.1) Gecko/20100101 Firefox/4.0.1"
}

def do_login(code):
    url = "http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=20196494202"

    data = {
        "email":"gaohj5@163.com",
        "icode":code,
        "origURL":"http://www.renren.com/home",
        "domain":"renren.com",
        "key_id":"1",
        "captcha_type":"web_login",
        "password":"829f2bc1ea294dddbd297cd9091518ecd7d413cb0b041194287c42e03b901674",
        "rkey":"a677c66e38dff0be2ff6315ba770ea33",
        "f":"http%3A%2F%2Fwww.renren.com%2F541197383%2Fnewsfeed%2Fphoto",


    }

    response = session.post(url,headers=headers,data=data)
    result = response.content.decode()
    print(result)

def get_code():
    #获取验证码的接口
    url = "http://icode.renren.com/getcode.do?t=web_login&rnd=%s" % str(random.random())
    res = session.get(url,headers=headers)
    with open('code.jpg','wb') as fp:
        fp.write(res.content)
        fp.flush()
    chaojiying = Chaojiying_Client('gaohj5', '12qwaszx', '900304')
    im = open('code.jpg', 'rb').read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    result = chaojiying.PostPic(im, 1902)['pic_str']
    print(result)
    return result

def get_profile():
    url = "http://www.renren.com/541197383/profile"
    response = session.get(url,headers=headers)
    print(response.content.decode())

if __name__ == "__main__":
    session = requests.session()
    #
    code = get_code()
    do_login(code)
    get_profile()
